<script lang="ts">
import { NSelect, selectProps, type SelectOption } from 'naive-ui'
import { defineComponent, h, shallowRef, onMounted, watch } from 'vue'
import { sendRequest } from '@/utils/api'

export default defineComponent({
  name: 'ThemeWordSelect',
  props: {
    ...selectProps,
    vars: {
      type: Object,
      defautl: () => ({})
    }
  },
  emits: ['update:value', 'updateValue'],
  setup(props, { emit }) {
    const options = shallowRef<SelectOption[]>([])
    const loading = shallowRef(false)

    const queryOptions = async () => {
      loading.value = true

      try {
        const [error, res] = await sendRequest({
          module: 'themeWords',
          api: 'options',
          override: {
            params: {  
              itemTypeCode:props.vars?.formData.BMCOM003
            }
          }
          // 参数
        })
        if (error) throw error
        if (res.code !== 0) throw new Error(res.msg)

        options.value = res.data
      } catch (error) {
        console.error(error)
      } finally {
        loading.value = false
      }
    }

    // 监听物品类型变化
    watch(
      () => props.vars?.formData.BMCOM003, // 改为formData.物品类型
      (v) => {
        queryOptions()
        console.log('change', v)
      },{
        immediate: true,
      }
    )
    onMounted(queryOptions)

    return () =>
      h(NSelect, {
        value: props.value,
        onUpdateValue: (v) => {
          emit('updateValue', v)
          emit('update:value', v)
        },
        options: options.value,
        loading: loading.value,
        disabled: props.disabled,
        clearable: props.clearable,
        labelField: props.labelField,
        valueField: props.valueField,
        placeholder: props.placeholder || '请选择主题词',
        multiple: props.multiple
      })
  }
})
</script>
